package com.matrix.im.interfaces.listener;

import com.matrix.common.constant.RocketMQConstants;
import com.matrix.im.domain.model.ChatMessage;
import com.matrix.im.domain.model.SystemMessage;
import com.matrix.im.service.SessionService;
import com.matrix.im.netty.MessagePusher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MessageBusListener {

    private final SessionService sessionService;
    private final MessagePusher messagePusher;

    @Component
    @RocketMQMessageListener(
            topic = RocketMQConstants.IM_PRIVATE_MESSAGE_TOPIC,
            consumerGroup = RocketMQConstants.IM_PRIVATE_MESSAGE_CONSUMER_GROUP
    )
    class PrivateMessageConsumer implements RocketMQListener<ChatMessage> {
        @Override
        public void onMessage(ChatMessage message) {
            log.debug("从总线接收到私聊消息: {}", message);
            try {
                if (sessionService.isUserConnectedToCurrentInstance(message.getToUserId())) {
                    log.info("当前实例 {} 正在处理用户 {} 的私聊消息 {}",
                            sessionService.getInstanceId(), message.getToUserId(), message.getId());
                    messagePusher.pushPrivateMessage(message);
                } else {
                    log.debug("消息 {} 的目标用户 {} 不在当前实例上。跳过推送。",
                            message.getId(), message.getToUserId());
                }
            } catch (Exception e) {
                log.error("处理私聊消息失败: {}", message.getId(), e);
            }
        }
    }

    @Component
    @RocketMQMessageListener(
            topic = RocketMQConstants.IM_SYSTEM_MESSAGE_TOPIC,
            consumerGroup = RocketMQConstants.IM_SYSTEM_MESSAGE_CONSUMER_GROUP
    )
    class SystemMessageConsumer implements RocketMQListener<SystemMessage> {
        @Override
        public void onMessage(SystemMessage message) {
            log.debug("从总线接收到系统消息: {}", message);
            try {
                if (sessionService.isUserConnectedToCurrentInstance(message.getUserId())) {
                    log.info("当前实例 {} 正在处理用户 {} 的系统消息 {}",
                            sessionService.getInstanceId(), message.getUserId(), message.getId());
                    messagePusher.pushSystemMessage(message);
                } else {
                    log.debug("系统消息 {} 的目标用户 {} 不在当前实例上。跳过推送。",
                            message.getId(), message.getUserId());
                }
            } catch (Exception e) {
                log.error("处理系统消息失败: {}", message.getId(), e);
            }
        }
    }
}
